package com.cash.app.ui.auth.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.cash.app.databinding.AcAuthPersonalOptionItemBinding
import com.cash.app.ui.auth.model.AuthOptionItem
import com.cash.app.utils.inVisible
import com.cash.app.utils.visible

class AuthOptionAdapter : RecyclerView.Adapter<AuthOptionAdapter.ViewHolder>() {

    private val items = mutableListOf<AuthOptionItem>()
    private var selectedPosition = -1
    var onItemClick: ((AuthOptionItem) -> Unit)? = null

    @SuppressLint("NotifyDataSetChanged")
    fun setData(newItems: List<AuthOptionItem>) {
        items.clear()
        items.addAll(newItems)
        notifyDataSetChanged()
    }

    fun getSelectedItem(): AuthOptionItem? {
        return if (selectedPosition >= 0) items[selectedPosition] else null
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = AcAuthPersonalOptionItemBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items[position], position)
    }

    inner class ViewHolder(
        private val binding: AcAuthPersonalOptionItemBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(item: AuthOptionItem, position: Int) {
            binding.apply {
                tvContent.text = item.name
                if (position == selectedPosition) {
                    ivSelected.visible()
                } else {
                    ivSelected.inVisible()
                }

                root.setOnClickListener {
                    val previousPosition = selectedPosition
                    selectedPosition = position
                    notifyItemChanged(previousPosition)
                    notifyItemChanged(selectedPosition)
                    onItemClick?.invoke(item)
                }
            }
        }
    }
} 